package sparqlclient;

import java.util.ArrayList;
import java.util.Map;

public class SparqlAnswerer implements SparqlInterface{
	
	
	private SparqlClient sparqlClient;
	private String prefix;
	
	public SparqlAnswerer (String endpointUri) {
		this.sparqlClient = new SparqlClient(endpointUri);
		
		this.prefix = "PREFIX : <http://ontologies.alwaysdata.net/space#>\n"
				+ "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
				+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
				+ "PREFIX owl:  <http://www.w3.org/2002/07/owl#>\n"
				+ "PREFIX xsd:  <http://www.w3.org/2001/XMLSchema#>\n";
	}

	@Override
	public boolean serverIsUp() {
		String query = "ASK WHERE { ?s ?p ?o }";
        boolean serverIsUp = true;//sparqlClient.ask(query);
        if (serverIsUp)
            System.out.println("server is UP");
        else
            System.out.println("service is DOWN");
        	
		return serverIsUp;
	}

	@Override
	public ArrayList<String> getSynonymes(String terme) {
		
		ArrayList<String> synonymes = new ArrayList<String>();
		
		String query = this.prefix
                + "SELECT ?label\n"
                + "WHERE {\n"
                + "   ?subject rdfs:label \"" + terme + "\"@fr.\n"
                + "   ?subject rdfs:label ?label.\n"
                + "}\n";
			
	    Iterable<Map<String, String>> results = sparqlClient.select(query);
	    for (Map<String, String> result : results) {
	    	if (terme.compareToIgnoreCase(result.get("label")) != 0) {
		        synonymes.add(result.get("label"));
	    	}
	    }
            
		return synonymes;
	}

	@Override
	public ArrayList<String> getTermesSpecialisant(String terme) {
		
		ArrayList<String> specialises = new ArrayList<String>();
		
		String query = this.prefix
                + "SELECT ?label\n"
                + "WHERE {\n"
                + "   ?subject rdfs:label \"" + terme + "\"@fr.\n"
                + "   ?subSubject rdfs:subClassOf ?subject.\n"
                + "   ?subSubject rdfs:label ?label.\n"
                + "}\n";
		
	    Iterable<Map<String, String>> results = sparqlClient.select(query);
	    for (Map<String, String> result : results) {
	    	specialises.add(result.get("label"));
	    }
            
		return specialises;
	}

	@Override
	public ArrayList<String> getEntites(String terme) {
		
		ArrayList<String> entites = new ArrayList<String>();
		
		String query = this.prefix
                + "SELECT ?label\n"
                + "WHERE {\n"
                + "   ?subject rdfs:label \"" + terme + "\"@fr.\n"
                + "   ?type rdf:type ?subject.\n"
                + "   ?type rdfs:label ?label.\n"
                + "}\n";
		
	    Iterable<Map<String, String>> results = sparqlClient.select(query);
	    for (Map<String, String> result : results) {
	    	entites.add(result.get("label"));
	    }
            
		return entites;
	}

}
